package class03;

import java.util.Arrays;

/**
 * @ClassName Code01_BSExist
 * @Description:
 * @Author: WangWenpeng
 * @date: 18:55 2021/5/23
 * @Version 1.0
 */
public class Code01_BSExist {


    /**
     * @Description 有序数组中找到num  二分法不断细分
     * @Author WangWenpeng
     * @Date 18:56 2021/5/23
     * @Param [arr, num]
     */
    public static boolean find(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return false;
        }

        int L = 0, R = arr.length - 1;
        while (L <= R) {
            int middle = (L + R) / 2;
            if (arr[middle] == num) {
                return true;
            } else if (arr[middle] < num) {
                L = middle + 1;
            } else {
                R = middle - 1;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        int testaTime = 10000, maxSize = 10, maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testaTime; i++) {
            int[] arr = generateRandomArray(maxSize, maxValue);
            Arrays.sort(arr);
            int value = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            if (test(arr, value) != find(arr, value)) {
                System.out.println("出错了！");
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");
    }

    //暴力遍历 判断是否含有
    private static boolean test(int[] arr, int value) {
        for (int cur : arr) {
            if (cur == value) {
                return true;
            }
        }
        return false;
    }

    //生成样本数据
    private static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
        }
        return arr;
    }
}
